package dao

import (
	"blogger/global"
	"blogger/model"
	"errors"
	"fmt"
	"time"
)

// 注册用户
func RegisterUser(userInfo model.UserInfo) (int64, error) {
	// 拼接sql
	sql := "insert into user(username, password, create_time, login_time, status) values(?, ?, ?, ?, ?)"
	// 获取stmt对象
	stmt, err := global.DB.Prepare(sql)
	if err != nil {
		return 0, errors.New("获取mysql连接错误")
	}
	// 执行sql
	result, err := stmt.Exec(userInfo.Username, userInfo.Password, userInfo.CreateTime, userInfo.LoginTime, userInfo.Status )
	if err != nil {
		return 0, errors.New("添加用户失败")
	}
	// 获取插入id
	insertId, _ := result.LastInsertId()
	return insertId, nil
}

// 通过username查询用户
func GetUserByUsername(username string) (model.UserInfo, error) {
	userInfo := &model.UserInfo{}
	// 拼接sql
	sqlStr := "SELECT id, username, password, create_time, login_time, status FROM user WHERE username = ?"
	err := global.DB.QueryRow(sqlStr, username).Scan(&userInfo.Id, &userInfo.Username, &userInfo.Password, &userInfo.CreateTime, &userInfo.LoginTime, &userInfo.Status)
	if err != nil {
		return *userInfo, errors.New("用户不存在")
	}
	return *userInfo, nil
}

// 更新用户登录时间
func UpdateUserInfoLoginTimeByUserId(id int64) {
	sqlStr := "UPDATE user SET login_time = ? WHERE id = ?"
	// 获取连接stmt
	stmt, err := global.DB.Prepare(sqlStr)
	if err != nil {
		fmt.Println("连接mysql失败")
	}
	stmt.Exec(time.Now().UnixNano()/1e6, id)
}
